﻿using System;
using System.Xml;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SharPointInventory
{
    public partial class MainForm : Form
    {
        #region Global Variables 
        Helper helper;
        int siteCount = 0;
        int backgroundProcessCount = 0;
        string progressStatus = string.Empty; 
        DateTime startDate = DateTime.Now;
        string webAppUrl = String.Empty; 
        SPWebApplication webApp = null;
        StreamWriter logFile = null;
        string dbName = string.Empty;
        string LargeSiteSize = string.Empty; 

        List<string> selectedDatabasesList = new List<string>();
        string selectedDatabasesId = string.Empty; 

        Microsoft.Office.Interop.Excel.ApplicationClass excelApp = null;
        System.Data.DataTable tableUnGhostedPages = null;
        System.Data.DataTable tableCheckedOutDocs = null;

        string _portalUrl = string.Empty;
        DataTable tableSiteCollectionStorageInfo;
        DataTable tableListVersionInfo;
        DataTable tableListLargeLists;
        DataTable tableSiteACLs;
        DataTable tableDatabasesInfo;
        DataTable tableSiteSolutions;
        DataTable tableListTemplates;

        DataTable tableSiteUsage;
        DataColumn colUSite;
        DataColumn colUDiscussionStorage;
        DataColumn colUHits;
        DataColumn colURecentMonth;
        DataColumn colUStorage;
        DataColumn colURecentDayHits;
        DataColumn colUBandWidth;
        DataColumn colLastContentModified;
        DataColumn colLastSecurityModified;
        DataColumn colUDatabase; 
        DataRow uRow;


        DataTable tablePortalUsageStats;
        DataColumn vColHits;
        DataColumn vColVisits;
        DataColumn vColStorage;
        DataColumn vColBandwidth;
        DataColumn vColRecentDay;
        DataColumn vColRecentMonth;
        DataColumn vColDiscussionStorage;
        DataRow vRow;

        DataTable webUsageTable;
        DataColumn webUsageHits;
        DataColumn webUsageRecentMonthHits;
        DataColumn webUsageRecentDayHits;
        DataRow webUsageRow;

        long TotalHits;
        long TotalVisits;
        long TotalRecentMonth;
        long TotalRecentDay; 
        long TotalStorage;
        long TotalBandwidth;
        long TotalDiscussionStorage;

        long uwebTotalHits;
        long uwebTotalRecentMonth;
        long uwebTotalMostRecentDayHits;
        
    #endregion 

        public MainForm()
        {
            InitializeComponent();

            tabControl1.TabPages["tabPage13"].Show();
            tabControl1.SelectTab("tabPage13"); 
            txtAboutMe.Text = "SharePoint 2010 Inventory (Release) Copyright (c) 2013 All rights reserved.\n\r" +
"Ver: 1.0.0.0 \n\r\r" +
"This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. \n\r" +
"If you have questions on the tool, then please email the author \n\r\r" +

"Developed by \n\r" +
"Godwin Tenzing  \n\r";

            txtTips.Text = "Please note, the tool was successfully used in a very large SharePoint farms, that has many terabytes of data.  For large SharePoint farms, the tool was designed to target selected areas.  Please follow the tips that are provided here to understand how to use the tool effectively. \n\r" +

"Tip 1 - In a large SharePoint farm, if you are unsure of running against all databases, then you can select one or more content databases. If you want to select specific content databases then unselect All Databases from the left hand side 'Select Content Database' control. \n\r" +

"Tip 2- Use the green section on the left to identify large site collections, large lists and site collections with large number of unique permissions.  \n\r" +

"Tip 3 - Use the red section on the left side to select the kind of information that you want to see as an output.  When you select certain time consuming operation on the red area, you will be prompted with a request for confirmation dialog window.  Please read the instruction and confirm or decline to run or to exclude time consuming operations. \n\r" +

"Tip 4 – Run the tool on a SharePoint server.  If you have a dedicated SharePoint Application server, then you can run the tool on an Application server, which is also running Microsoft SharePoint Foundation Web Application Service.  The tool is not CPU & DISK IO intensive.  However, the amount of RAM it will consume will depend on the options that you select on the green and red area.  Please ensure the server has at least 1.5 or 2gb free memory.  Though, the tool will not consume or require so much memory.  It is best practice to have sufficient memory on the server for server stability. \n\r" +

"Tip 5 - To run the tool, run the tool using an account that is local admin on the SharePoint server and also part of the Farm administrator group within SharePoint. "; 

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                helper = new Helper();
                ListItemCollection items = helper.GetWebApplicationList();

                foreach (ListItem item in items)
                {
                    cbListWebApps.Items.Add(item);
                }

                #region Delete the error Log if it already exists
                if (File.Exists("Error.log"))
                {
                    File.Delete("Error.log");
                }

                logFile = new StreamWriter("Error.log");
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region Methods 

        /// <summary>
        /// Populate Site Collection list on the Dropdown controls that displays the Site Collection List
        /// </summary>
        /// <param name="webApp"></param>
        /// <param name="strPopulateWhat"></param>
        public void LoadSiteCollections(SPWebApplication webApp, string strPopulateWhat)
        {
            SPSiteCollection siteCollections = null;

            try
            {
                if (strPopulateWhat == "" || strPopulateWhat == "All")
                {

                    cbListSiteCollections.Items.Clear();
                    cblistSiteCollectionstoLock.Items.Clear();
                    cbListSiteCollectionsforWebUsage.Items.Clear();

                    foreach (SPContentDatabase db in webApp.ContentDatabases)
                    {
                        try
                        {
                            if (selectedDatabasesList.Contains("All Databases"))
                            {
                                siteCollections = webApp.Sites;

                                BuildSiteCollectionsList(siteCollections);
                                return;
                            }
                            else if (selectedDatabasesList.Contains(db.Name))
                            {
                                siteCollections = db.Sites;
                                BuildSiteCollectionsList(siteCollections);
                            }
                        }
                        catch (SPException spEx) { ErrorLog("Error Module chkShowSitesfromDBs_CheckedChanged - " + spEx.Message); }
                        catch (Exception ex) { ErrorLog("Error Module chkShowSitesfromDBs_CheckedChanged - " + ex.Message); }

                    }
                }
                else if (strPopulateWhat == "ShowLockedSites")
                {
                    cblistSiteCollectionstoLock.Items.Clear();

                    foreach (SPSite site in siteCollections)
                    {
                        string siteName = site.Url.ToString();

                        try
                        {
                            if (site.ReadLocked == true || site.WriteLocked == true || site.ReadOnly == true)
                            {
                                cblistSiteCollectionstoLock.Items.Add(new ListItem(siteName, site.Url.ToString()));
                                cblistSiteCollectionstoLock.Update();
                            }
                        }
                        catch (System.ApplicationException appEx)
                        {
                            if (appEx.Message.Contains("blocked"))
                            {
                                cblistSiteCollectionstoLock.Items.Add(new ListItem(siteName, siteName));
                                cblistSiteCollectionstoLock.Update();
                            }
                            else
                            { }
                        }
                        catch (Exception ex) { ErrorLog("Error occurred on method LoadSiteCollections - " + ex.Message); }

                        site.Dispose();
                    }
                }
            }
            catch (SPException spEx) { ErrorLog("Error occurred on method LoadSiteCollections - " + spEx.Message); }
            catch (Exception ex) { ErrorLog("Error occurred on method LoadSiteCollections - " + ex.Message); }
        }

        private void BuildSiteCollectionsList(SPSiteCollection siteCollection)
        {
            foreach (SPSite site in siteCollection)
            {
                try
                {
                    string siteName = site.Url.ToString();
                    cbListSiteCollections.Items.Add(new ListItem(siteName, site.Url.ToString()));
                    cbListSiteCollections.Update();

                    if (chkDisplaySiteUsage.Checked == true)
                    {
                        cbListSiteCollectionsforWebUsage.Items.Add(new ListItem(siteName, site.Url.ToString()));
                        cbListSiteCollectionsforWebUsage.Update();
                    }


                    cblistSiteCollectionstoLock.Items.Add(new ListItem(siteName, site.Url.ToString()));
                    cblistSiteCollectionstoLock.Update();

                }
                catch (SPException spEx) { ErrorLog(spEx.Message); }
                catch (Exception ex) { ErrorLog("Error occurred on method LoadSiteCollections - " + ex.Message); }
            }
        }

        /// <summary>
        /// Load Content Database Details. 
        /// </summary>
        /// <param name="webApp"></param>
        public void LoadContentDBDetails(SPWebApplication webApp)
        {
            //listContentDatabase.Items.Clear();

            tableDatabasesInfo = helper.CreateTabletoStoreDatabaseInfo();

            foreach (SPContentDatabase db in webApp.ContentDatabases)
            {
                try
                {
                    DataRow row = tableDatabasesInfo.NewRow();
                    row["Name"] = db.Name;
                    row["Disk size required to backup in GB"] = helper.ConvertBytestoGB(db.DiskSizeRequired);
                    row["Current SiteCount"] = db.CurrentSiteCount;
                    row["Warning SiteCount"] = db.WarningSiteCount;
                    row["Maximum SiteCount"] = db.MaximumSiteCount;
                    row["SQLServer Instance"] = db.Server;
                    row["Status"] = db.Status;
                    row["ID"] = db.Id.ToString();
                    tableDatabasesInfo.Rows.Add(row);
                }
                catch (SPException spEx) { ErrorLog(spEx.Message); }
            }
        }

        /// <summary>
        /// Populate SharePoint Web Application Usage Summary 
        /// </summary>
        private void PopulatePortalStats()
        {
            try
            {
                tablePortalUsageStats = new DataTable();

                vColBandwidth = new DataColumn();
                vColBandwidth.ColumnName = "TotalBandwidth";

                vColDiscussionStorage = new DataColumn();
                vColDiscussionStorage.ColumnName = "TotalDiscussionStorage";

                vColHits = new DataColumn();
                vColHits.ColumnName = "TotalHits";

                vColStorage = new DataColumn();
                vColStorage.ColumnName = "TotalStorage";

                vColVisits = new DataColumn();
                vColVisits.ColumnName = "TotalVisits";

                vColRecentMonth = new DataColumn();
                vColRecentMonth.ColumnName = "TotalRecentMonth";

                vColRecentDay = new DataColumn();
                vColRecentDay.ColumnName = "TotalRecentDay"; 

                //tablePortalUsageStats.Columns.Add(vColHits);
                //tablePortalUsageStats.Columns.Add(vColVisits);
                tablePortalUsageStats.Columns.Add(vColRecentMonth);
                tablePortalUsageStats.Columns.Add(vColRecentDay);
                tablePortalUsageStats.Columns.Add(vColStorage);
                tablePortalUsageStats.Columns.Add(vColBandwidth);
                tablePortalUsageStats.Columns.Add(vColDiscussionStorage);

                vRow = tablePortalUsageStats.NewRow();

                //vRow["TotalHits"] = TotalHits;
                //vRow["TotalVisits"] = TotalVisits;
                vRow["TotalRecentMonth"] = TotalRecentMonth;
                vRow["TotalRecentDay"] = TotalRecentDay;
                vRow["TotalStorage"] = TotalStorage;
                vRow["TotalBandwidth"] = TotalBandwidth;
                vRow["TotalDiscussionStorage"] = TotalDiscussionStorage;

                tablePortalUsageStats.Rows.Add(vRow);

                
            }
            catch (Exception ex)
            {
                ErrorLog("Error occurred on method PopulatePortalStats - " + ex.Message); 
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Pouplate SharePoint site (SPWeb) Usage Stats Summary 
        /// </summary>
        private void populateWebUsageSummary()
        {
            try
            {
                gridWebUsageSummary.DataSource = null;
                webUsageTable = new DataTable();
                webUsageHits = new DataColumn();
                webUsageHits.ColumnName = "Total Hits";
                webUsageRecentMonthHits = new DataColumn();
                webUsageRecentMonthHits.ColumnName = "Recent Month Hits";
                webUsageRecentDayHits = new DataColumn();
                webUsageRecentDayHits.ColumnName = "Most Recent Day Hits";
                webUsageTable.Columns.Add(webUsageHits);
                webUsageTable.Columns.Add(webUsageRecentMonthHits);
                webUsageTable.Columns.Add(webUsageRecentDayHits);
                webUsageRow = webUsageTable.NewRow();
                webUsageRow["Total Hits"] = uwebTotalHits;
                webUsageRow["Recent Month Hits"] = uwebTotalRecentMonth;
                webUsageRow["Most Recent Day Hits"] = uwebTotalMostRecentDayHits;
                webUsageTable.Rows.Add(webUsageRow);
                gridWebUsageSummary.DataSource = webUsageTable;
            }
            catch (Exception ex)
            {
                ErrorLog("Error occurred on method populateWebUsageSummary - " + ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Populate SharePoint Web Usage Data 
        /// </summary>
        /// <param name="siteUrl"></param>
        private void populateWebUsageData(string siteUrl)
        {
            try
            {
                DataTable table = null;
                dataGridWebUsageData.DataSource = null;

                using (SPSite site = new SPSite(siteUrl))
                {
                    try
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            try
                            {
                                table = web.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);

                                if (table != null)
                                {
                                    foreach (DataRow row in table.Rows)
                                    {
                                        try
                                        {
                                            if (row["Total Hits"] != null)
                                                uwebTotalHits = uwebTotalHits + Convert.ToInt32(row["Total Hits"]);
                                            if (row["Recent Month"] != null)
                                                uwebTotalRecentMonth = uwebTotalRecentMonth + Convert.ToInt32(row["Recent Month"]);
                                            if (row["Most Recent Day Hits"] != null)
                                                uwebTotalMostRecentDayHits = uwebTotalMostRecentDayHits + Convert.ToInt32(row["Most Recent Day Hits"]);
                                        }
                                        catch { }
                                    }

                                    //table.Columns.Remove("Bandwidth");
                                    //table.Columns.Remove("Discussion Storage");
                                    dataGridWebUsageData.DataSource = table;
                                }
                            }
                            catch (SPException spEx) { ErrorLog("Error occurred on method populateWebUsageData - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error occurred on method populateWebUsageData - " + ex.Message); }

                        }
                    }
                    catch (SPException spExx) { ErrorLog("Error occurred on method populateWebUsageData - " + spExx.Message); }
                    catch (Exception ex) { ErrorLog("Error occurred on method populateWebUsageData - " + ex.Message); }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                ErrorLog("Error occurred on method populateWebUsageData - " + ex.Message);
            }
        }

        /// <summary>
        /// Populate the last 30 days Daily Page / document Usage Data 
        /// </summary>
        /// <param name="siteUrl"></param>
        private void populateDailyWebUsageData(string siteUrl)
        {
            try
            {
                DataTable table = null;
                gridDailyUsageData.DataSource = null;

                using (SPSite site = new SPSite(siteUrl))
                {
                    try
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            try
                            {
                                table = web.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.day);

                                if (table != null)
                                {
                                    gridDailyUsageData.DataSource = table;
                                }
                            }
                            catch (SPException spEx) { ErrorLog("Error occurred on populateDailyWebUsageData - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error occurred on populateDailyWebUsageData - " + ex.Message); }
                        }
                    }
                    catch (SPException spExx) { ErrorLog("Error occurred on populateDailyWebUsageData - " + spExx.Message); }
                    catch (Exception ex) { ErrorLog("Error occurred on populateDailyWebUsageData - " + ex.Message); }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Populate Larlge List Results 
        /// </summary>
        /// <param name="list"></param>
        /// <param name="table"></param>
        /// <param name="webUrl"></param>
        private void AddRowstoListTable(SPList list, System.Data.DataTable table, string webUrl)
        {
            try
            {
                DataRow rowList = table.NewRow();
                rowList["List Name"] = list.Title;
                rowList["Site Url"] = webUrl;
                rowList["Total Items"] = list.ItemCount;
                rowList["Last Item Modified Date"] = list.LastItemModifiedDate;
                table.Rows.Add(rowList);
            }
            catch { }
        }

        /// <summary>
        /// Display Unghosted  & Checked out pages from SharePoint libraries. 
        /// </summary>
        private void PopulateUnGhostedPagesandCheckedOutFiles()
        {
            try
            {
                tableUnGhostedPages = null;
                gridCustomizedPages.DataSource = null;
                tableUnGhostedPages = helper.CreateTabletoStoreUnghostedPages();

                tableCheckedOutDocs = null;
                dataGridCheckedOutDocs.DataSource = null;
                tableCheckedOutDocs = helper.CreateTabletoStoreCheckedOutDocs();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                   {
                       foreach (SPSite site in webApp.Sites)
                       {
                           try
                           {
                               foreach (SPWeb web in site.AllWebs)
                               {
                                   try
                                   {
                                       string url = web.Url + "/";

                                       //Iterate via Files from the website root 
                                       foreach (SPFile file in web.Files)
                                       {
                                           try
                                           {
                                               string listUrl = web.Url + "/" + file.Url;
                                               helper.AddRowstoUnGhostedPagesTable(file, tableUnGhostedPages, listUrl);
                                               helper.AddRowstoCheckedOutDocsTable(file, tableCheckedOutDocs, listUrl);
                                           }
                                           catch (SPException spEx) { ErrorLog("Error occurred on method PopulateUnGhostedPagesandCheckedOutFiles - " + spEx.Message); }
                                       }

                                       // Iterate via files that are within Library and folders. 
                                       foreach (SPFolder folder in web.Folders)
                                       {
                                           try
                                           {
                                               RecursiveFolders(folder, tableCheckedOutDocs, url);

                                               if (chkIncludeCustomizedPagesFromLibraries.Checked == true)
                                               {
                                                   RecursiveFolders(folder, tableUnGhostedPages, url);
                                               }
                                           }
                                           catch (SPException spEx) { ErrorLog("Error occurred on method PopulateUnGhostedPagesandCheckedOutFiles - " + spEx.Message); }
                                       }


                                   }
                                   catch (SPException spEx) { ErrorLog("Error Module PopulateUnGhostedPagesandCheckedOutFiles - " + spEx.Message); }
                                   catch (Exception ex) { ErrorLog("Error Module PopulateUnGhostedPagesandCheckedOutFiles - " + ex.Message); } 
                                   finally
                                   {
                                       web.Close();
                                       web.Dispose();
                                   }
                               }
                           }
                           catch (SPException spEx) { ErrorLog("Error Module PopulateUnGhostedPagesandCheckedOutFiles - " + spEx.Message); }
                           catch (Exception ex) { ErrorLog("Error Module PopulateUnGhostedPagesandCheckedOutFiles - " + ex.Message); } 
                           site.Close();
                           site.Dispose();
                       }
                   });

                gridCustomizedPages.DataSource = tableUnGhostedPages;
                dataGridCheckedOutDocs.DataSource = tableCheckedOutDocs;
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message); 
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Populate Sites with Large ACL Info 
        /// </summary>
        private void PopulateACLInfoGrid()
        {
            try
            {
                string strWebApp = cbListWebApps.SelectedItem.ToString();
                Uri strUrl = new Uri(helper.ReturnWebAppURL(strWebApp));
                webApp = SPWebApplication.Lookup(strUrl);

                DataTable tableSiteACLs = helper.CreateTabletoStoreSiteACLs();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                    {

                        foreach (SPSite site in webApp.Sites)
                        {
                            try
                            {
                                #region Site Collection ACL Info
                                SPWeb rootWeb = site.RootWeb;
                                DataRow rowACLs = tableSiteACLs.NewRow();
                                rowACLs["Sites with large number of ACLs"] = rootWeb.Url;
                                rowACLs["Total Unique Users or Groups"] = rootWeb.SiteUsers.Count;
                                tableSiteACLs.Rows.Add(rowACLs);
                                #endregion

                                if (site != null)
                                    site.Dispose();
                            }
                            catch (SPException spEx) { ErrorLog("Error Module - PopulateACLInfoGrid - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error Module - PopulateACLInfoGrid - " + ex.Message); } 
                        }
                    });

                gridSiteswithLargeACLs.DataSource = tableSiteACLs;
            }
            catch (SPException spEx)
            {
                ErrorLog("Error occurred on PopulateACLInfoGrid - " + spEx.Message); 
                MessageBox.Show(spEx.Message);
            }
            catch (Exception ex)
            {
                ErrorLog("Error occurred on PopulateACLInfoGrid - " + ex.Message); 
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Display Vital Site Collection Infos. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbListSiteCollections_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbListSiteCollections.SelectedItem != null)
            {

                if (txtNoofRecords.Text == "")
                    txtNoofRecords.Text = "50";

                uint maxNoofRecords = Convert.ToUInt32(txtNoofRecords.Text);


                using (SPSite site = new SPSite(cbListSiteCollections.Text))
                {
                    try
                    {
                        #region Key Site Collection Info

                        lblAllowRSSFeeds.Text = site.AllowRssFeeds.ToString();
                        //site.AllowUnsafeUpdates;
                        if (webApp.AutomaticallyDeleteUnusedSiteCollections == true)
                        {
                            lblAutomaticDeletion.Text = site.CertificationDate.ToShortDateString();
                        }

                        lblAnonymous.Text = site.IISAllowsAnonymous.ToString();
                        lblHostHeaderSite.Text = site.HostHeaderIsSiteName.ToString();
                        lblContentModified.Text = site.LastContentModifiedDate.ToString();
                        lblSecurityModified.Text = site.LastSecurityModifiedDate.ToString();

                        if (site.Quota.StorageMaximumLevel == 0)
                            lblQuota.Text = "No Quota";
                        else
                            lblQuota.Text = site.Quota.StorageMaximumLevel.ToString();

                        lblPrimaryAdmin.Text = site.Owner.LoginName;

                        try
                        {
                            lblSecondaryAdmin.Text = site.SecondaryContact.LoginName;
                        }
                        catch { }

                        lblSiteCollectionHits.Text = site.Usage.Hits.ToString();
                        lblSiteCollectionVisits.Text = site.Usage.Visits.ToString();
                        lblSiteCollectionStorage.Text = site.Usage.Storage.ToString();
                        lblSiteCollectionBandwidth.Text = site.Usage.Bandwidth.ToString();
                        lblSiteDiscussionStorage.Text = site.Usage.DiscussionStorage.ToString();


                        #endregion

                        #region Get Site Collection Storage Statistics
                        DataTable tableDocs = site.StorageManagementInformation(SPSite.StorageManagementInformationType.Document, SPSite.StorageManagementSortOrder.Decreasing, SPSite.StorageManagementSortedOn.Size, maxNoofRecords);
                        tableDocs = helper.processDocumentStatsInfo(tableDocs);
                        gridDocumentStats.DataSource = tableDocs;

                        DataTable tableLibrary = site.StorageManagementInformation(SPSite.StorageManagementInformationType.DocumentLibrary, SPSite.StorageManagementSortOrder.Decreasing, SPSite.StorageManagementSortedOn.Size, maxNoofRecords);
                        tableLibrary = helper.processListLibraryStatsInfo(tableLibrary);
                        gridDocumentLibraryStats.DataSource = tableLibrary;

                        DataTable tableList = site.StorageManagementInformation(SPSite.StorageManagementInformationType.List, SPSite.StorageManagementSortOrder.Decreasing, SPSite.StorageManagementSortedOn.Size, maxNoofRecords);
                        tableList = helper.processListLibraryStatsInfo(tableList);
                        gridListStats.DataSource = tableList;

                        #endregion

                        #region Get Key Site Information

                        DataTable tableSite = helper.CreateSiteInfoTable();

                        foreach (SPWeb web in site.AllWebs)
                        {
                            try
                            {
                                DataRow row = tableSite.NewRow();
                                row["Site URL"] = web.Url;
                                row["Title"] = web.Title;
                                row["Template Name"] = web.WebTemplate + "#" + web.WebTemplateId.ToString();
                                row["Created"] = web.Created.ToString();
                                row["Last Modified"] = web.LastItemModifiedDate;
                                row["Anonymous"] = web.AllowAnonymousAccess.ToString();
                                row["Allow RSSFeeds"] = web.AllowRssFeeds.ToString();
                                row["Presence On"] = web.PresenceEnabled.ToString();
                                row["Unique Permission"] = web.HasUniqueRoleAssignments.ToString();
                                row["No Crawl"] = web.NoCrawl.ToString();
                                row["Request Access On"] = web.RequestAccessEnabled;
                                tableSite.Rows.Add(row);
                            }
                            catch (SPException spEx) { ErrorLog("Error occurred on event cbListSiteCollections_SelectedIndexChanged - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error occurred on event cbListSiteCollections_SelectedIndexChanged - " + ex.Message); }
                        }
                        gridSiteTemplate.DataSource = tableSite;

                        #endregion

                    }
                    catch (SPException spEx)
                    {
                        ErrorLog("Error occured on event - cbListSiteCollections_SelectedIndexChanged - " + "Unable to retrieve site collection/ web info: " + spEx.Message);
                    }
                    catch (System.Data.DataException dataEx)
                    {
                        ErrorLog("Error occured on event - cbListSiteCollections_SelectedIndexChanged - " + "Unable to get site collection/ web info: " + dataEx.Message);
                    }
                    catch (Exception ex)
                    {
                        ErrorLog("Error occured on event - cbListSiteCollections_SelectedIndexChanged - " + "Unable to get  site collection/ web info: " + ex.Message);
                    }
                }
            }
        }    

        /// <summary>
        /// Iterate via SharePoint folders and subfolders to check for Checked Out and Unghosted pages. 
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="table"></param>
        /// <param name="url"></param>
        private void RecursiveFolders(SPFolder folder, System.Data.DataTable table, string url)
        {
            foreach (SPFile file in folder.Files)
            {
                try
                {
                    string listUrl = url + "/" + file.Url;
                    if (table.TableName == "CheckedOut Docs")
                    {
                        helper.AddRowstoCheckedOutDocsTable(file, table, listUrl);
                    }
                    else if (table.TableName == "UnGhostedPages")
                        helper.AddRowstoUnGhostedPagesTable(file, table, listUrl);
                }
                catch (SPException spEx) { ErrorLog("Error Module - RecursiveFolders - " + spEx.Message); } 
                catch (Exception ex) { ErrorLog("Error Module - RecursiveFolders - "  + ex.Message); } 
            }

            if (folder.SubFolders.Count > 0)
            {
                foreach (SPFolder subFolder in folder.SubFolders)
                {
                    try
                    {
                        RecursiveFolders(subFolder, table, url);
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="obj"></param>
        public void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// Reusable method to Log any Errors on processing the data 
        /// </summary>
        /// <param name="strErrorMsg"></param>
        public void ErrorLog(string strErrorMsg)
        {
            logFile.WriteLine(DateTime.Now + "  " + strErrorMsg);
            logFile.Flush();
        }

        #endregion 

        #region Button event to export reports
        private void btnExportSiteTemplates_Click(object sender, EventArgs e)
        {
            if (gridCustomSiteSolutions.RowCount > 0)
            {
                ExportDataGridViewtoExcelFile(gridCustomSiteSolutions, "Report_CustomSiteTemplates");
                MessageBox.Show("Report file generated successfuly");
            }
        }

        /// <summary>
        /// Export DataGridView Results to Excel file
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="filename"></param>
        private void ExportDataGridViewtoExcelFile(DataGridView gridView, string filename)
        {
            try
            {
                string appPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
                string path = appPath + "\\" + filename + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + ".csv";

                using (StreamWriter fileStream = new StreamWriter(path))
                {
                    int rowcount = gridView.RowCount;
                    int colcount = gridView.ColumnCount;

                    for (int i = 0; i < rowcount; i++)
                    {
                        string strRowVal = "";
                        if (i == 0)
                        {
                            #region Write Header Text
                            for (int j = 0; j < colcount; j++)
                            {

                                if (strRowVal == "")
                                {
                                    strRowVal = gridView.Columns[j].HeaderText;
                                }
                                else
                                {
                                    strRowVal = strRowVal + " |" + gridView.Columns[j].HeaderText;
                                }
                            }
                            fileStream.WriteLine(strRowVal);
                        }
                            #endregion

                        strRowVal = "";
                        for (int j = 0; j < colcount; j++)
                        {
                            if (gridView.RowCount == 0)
                            {
                                strRowVal = gridView.Columns[j].HeaderText;
                            }

                            if (strRowVal == "")
                            {
                                strRowVal = gridView.Rows[i].Cells[j].Value.ToString();
                            }
                            else
                            {
                                strRowVal = strRowVal + " |" + gridView.Rows[i].Cells[j].Value.ToString();
                            }
                        }
                        fileStream.WriteLine(strRowVal);
                        //fileStream.WriteLine(gridView.Rows[i].Cells[0].Value.ToString() + "\t" + gridView.Rows[i].Cells[1].Value.ToString() + "\t\t" + gridView.Rows[i].Cells[2].Value.ToString());
                    }

                    fileStream.Close();//Don’t Forget Close the TextWriter Object(sw)            MessageBox.Show("Data Successfully Exported");
                }
            }
            catch (System.Runtime.InteropServices.COMException comEx)
            {
                MessageBox.Show(null, comEx.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(null, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                //releaseObject(excelApp);
            }
        }

        private void btnExportListTemplates_Click(object sender, EventArgs e)
        {
            if (gridListTemplates.RowCount > 0)
            {
                ExportDataGridViewtoExcelFile(gridListTemplates, "Report_CustomListTemplates");
                MessageBox.Show("Report file generated successfuly");
            }
        }

        private void btnExportListswithUnlimitedVersions_Click(object sender, EventArgs e)
        {
            if (gridListVersionInfo.RowCount > 0)
                ExportDataGridViewtoExcelFile(gridListVersionInfo, "Report_ListsWithUnlimitedVersions");
            MessageBox.Show("Report file generated successfuly");
        }

        private void btnExportLargeSitestoExcel_Click(object sender, EventArgs e)
        {
            if (gridSiteCollections.RowCount > 0)
            {
                ExportDataGridViewtoExcelFile(gridSiteCollections, "Report_LargeSiteCollections");
                MessageBox.Show("Report file generated successfuly");
            }
        }


        private void btnExportLargeListstoExcel_Click(object sender, EventArgs e)
        {
            if (gridLargeLists.RowCount > 0)
            {
                ExportDataGridViewtoExcelFile(gridLargeLists, "Report_LargeSharePointLists");
                MessageBox.Show("Report file generated successfuly");
            }
        }

        private void btnExportSiteswithLargeACLs_Click(object sender, EventArgs e)
        {
            if (gridSiteswithLargeACLs.RowCount > 0)
            {
                ExportDataGridViewtoExcelFile(gridSiteswithLargeACLs, "Report_SiteswithLargeACLs");
                MessageBox.Show("Report file generated successfuly");
            }
        }


        #endregion

        #region Background Process to retrieve SharePoint Data Stats 

        private int FindTotalSiteCountFromSelectedDatabases()
        {
            foreach (SPContentDatabase db in webApp.ContentDatabases)
            {
                try
                {
                    if (selectedDatabasesList.Contains(db.Name))
                    {
                        siteCount = siteCount + db.Sites.Count;
                    }
                }
                catch (SPException spEx) { ErrorLog("Error Module FindTotalSiteCountFromSelectedDatabases - " + spEx.Message); }
                catch (Exception ex) { ErrorLog("Error Module FindTotalSiteCountFromSelectedDatabases - " + ex.Message); }
            }
            return siteCount; 
        }

        private void ProcessandPopulateLargeObjectData(SPSiteCollection Sites)
        {
            string strSites = txtIssueSites.Text;
            
            
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                #region Iterate Site Collection & Gather Data

                
                foreach (SPSite site in Sites)
                {
                    try
                    {
                        bool isProcessSite = true; 

                        if (strSites != "")
                        {
                            string[] issuesSites = System.Text.RegularExpressions.Regex.Split(strSites, "\r\n");
                            string str1 = string.Empty;

                            try
                            {
                                for (int i = 0; i <= issuesSites.Length; i++)
                                {
                                    string str = issuesSites[i];

                                    if (str[str.Length - 1] == '/')
                                        str = str.Substring(0, str.Length - 1);

                                    if (str.Equals(site.Url))
                                        isProcessSite = false;
                                }
                            }
                            catch { }
                        }

                        if (isProcessSite == true)
                        {
                            long RecentMonth = 0;
                            long Hits = 0;
                            long RecentDayHits = 0;

                            if (chkDisplayLargeSites.Checked == true)
                            {
                                #region Site Collection Storage Info
                                int binItemCount = 0;
                                long binSize = 0;

                                string Str = LargeSiteSize.Trim();
                                double Num;
                                bool isNum = double.TryParse(Str, out Num);

                                if (LargeSiteSize == "" || isNum == false)
                                    LargeSiteSize = "250";

                                if (helper.ConvertBytestoMB(site.Usage.Storage) >= Convert.ToInt64(LargeSiteSize))
                                {
                                    site.GetRecycleBinStatistics(out binItemCount, out binSize);
                                    DataRow row = tableSiteCollectionStorageInfo.NewRow();
                                    row["Site Url"] = site.Url;
                                    row["Total Size in MB"] = helper.ConvertBytestoMB(site.Usage.Storage);
                                    row["Discussions Size in MB"] = helper.ConvertBytestoMB(site.Usage.DiscussionStorage);
                                    row["Quota Size in MB"] = helper.ConvertBytestoMB(site.Quota.StorageMaximumLevel);
                                    row["LastContentModifiedDate"] = site.LastContentModifiedDate;
                                    row["LastSecurityModifiedDate"] = site.LastSecurityModifiedDate; ;
                                    row["Recyclebin Items"] = binItemCount;
                                    row["Recyclebin Size in MB"] = helper.ConvertBytestoMB(binSize);
                                    tableSiteCollectionStorageInfo.Rows.Add(row);
                                }

                                #endregion
                            }

                            if (chkDisplayLargeACLS.Checked == true)
                            {
                                #region Site Collection ACL Info

                                if (site.RootWeb.SiteUsers.Count > Convert.ToInt32(txtLargeACLs.Text))
                                {
                                    SPWeb rootWeb = site.RootWeb;

                                    try
                                    {
                                        DataRow rowACLs = tableSiteACLs.NewRow();
                                        rowACLs["Sites with large number of ACLs"] = rootWeb.Url;
                                        rowACLs["Total Unique Users or Groups"] = rootWeb.SiteUsers.Count;
                                        tableSiteACLs.Rows.Add(rowACLs);
                                    }
                                    catch { }
                                }
                                #endregion
                            }

                            SPWeb rootweb = site.RootWeb;
                            if (chkDisplayTemplates.Checked == true)
                            {
                                #region Display Site and List Templates

                                foreach (SPUserSolution solution in site.Solutions)
                                {
                                    try
                                    {
                                        DataRow row = tableSiteSolutions.NewRow();
                                        row["Name"] = solution.Name;
                                        row["SolutionId"] = solution.SolutionId;
                                        row["Status"] = solution.Status;
                                        row["Signature"] = solution.Signature;
                                        row["HasAssemblies"] = solution.HasAssemblies;
                                        tableSiteSolutions.Rows.Add(row);
                                    }
                                    catch { }
                                }

                                SPList listLists = rootweb.Lists["List Template Gallery"];

                                foreach (SPListItem item in listLists.Items)
                                {
                                    try
                                    {
                                        string listTemplateName = item["Name"].ToString();

                                        DataRow row = tableListTemplates.NewRow();
                                        row["Template Name"] = listTemplateName;
                                        row["Site URL"] = rootweb.Url;
                                        tableListTemplates.Rows.Add(row);
                                    }
                                    catch { }
                                }
                                #endregion
                            }


                            foreach (SPWeb web in site.AllWebs)
                            {
                                try
                                {
                                    foreach (SPList list in web.Lists)
                                    {
                                        try
                                        {
                                            string webUrl = web.Url;

                                            if (chkDisplayUnlimitedListVersions.Checked == true)
                                            {
                                                #region Identify List Item Versions
                                                if (list.EnableVersioning == true && list.MajorVersionLimit.Equals(0))
                                                {

                                                    if (chkIncludeHiidenLists.Checked == true)
                                                        AddRowstoListTable(list, tableListVersionInfo, webUrl);

                                                    else
                                                    {
                                                        if (list.Hidden == false)
                                                            AddRowstoListTable(list, tableListVersionInfo, webUrl);
                                                    }
                                                }
                                                #endregion

                                                if (chkDisplayLargeACLS.Checked == true)
                                                {
                                                    #region List ACL Info

                                                    if (list.HasUniqueRoleAssignments == true)
                                                    {
                                                        foreach (SPPermission permission in list.Permissions)
                                                        {
                                                            try
                                                            {
                                                                string str = permission.Member.ToString();
                                                            }
                                                            catch { }
                                                        }
                                                    }
                                                    #endregion
                                                }
                                            }

                                            if (chkDisplayLargeLists.Checked == true)
                                            {
                                                #region Identify Large Lists
                                                int itemThreshold = 1999;

                                                if (txtItemCountThreshold.Text != "")
                                                    itemThreshold = Convert.ToInt32(txtItemCountThreshold.Text);

                                                if (list.ItemCount >= itemThreshold)
                                                {
                                                    if (chkIncludeHiddenLargeList.Checked == true)
                                                        AddRowstoListTable(list, tableListLargeLists, webUrl);
                                                    else
                                                    {
                                                        if (list.Hidden == false)
                                                            AddRowstoListTable(list, tableListLargeLists, webUrl);
                                                    }
                                                }
                                                #endregion
                                            }
                                        }
                                        catch (Exception subex)
                                        {
                                            ErrorLog("Error occurrred on method ProcessandPopulateLargeObjectData - " + subex.Message);
                                        }

                                        #region Web Usage Recent Month data
                                        DataTable webtable = web.GetUsageData(SPUsageReportType.url, SPUsagePeriodType.lastMonth);
                                        if (webtable != null)
                                        {
                                            foreach (DataRow irow in webtable.Rows)
                                            {
                                                try
                                                {
                                                    RecentMonth = RecentMonth + Convert.ToInt64(irow["Recent Month"]);
                                                    RecentDayHits = RecentDayHits + Convert.ToInt64(irow["Most Recent Day Hits"]);
                                                    Hits = Hits + Convert.ToInt64(irow["Total Hits"]);
                                                }
                                                catch { }
                                            }
                                            webtable.Dispose();
                                        }
                                        #endregion
                                    }
                                }
                                catch (SPException spEx) { ErrorLog("Error Module ProcessandPopulateLargeObjectData - " + spEx.Message); }
                                catch (Exception ex) { ErrorLog("Error Module ProcessandPopulateLargeObjectData - " + ex.Message); }

                                web.Close();
                                web.Dispose();
                            }

                            uRow = tableSiteUsage.NewRow();
                            uRow["SiteCollection URL"] = site.Url;
                            //uRow["Hits"] = Hits;
                            //uRow["Visits"] = site.Usage.Visits;
                            uRow["RecentDayHits"] = RecentDayHits;
                            uRow["Storage"] = site.Usage.Storage;
                            uRow["Bandwidth"] = site.Usage.Bandwidth;
                            uRow["DiscussionStorage"] = site.Usage.DiscussionStorage;
                            uRow["Recent Month"] = RecentMonth;
                            uRow["Last Content Modified"] = site.LastContentModifiedDate;
                            uRow["Last Security Modified"] = site.LastSecurityModifiedDate;
                            uRow["Content Database"] = site.ContentDatabase.Name;
                            tableSiteUsage.Rows.Add(uRow);

                            TotalBandwidth += site.Usage.Bandwidth;
                            TotalDiscussionStorage += site.Usage.DiscussionStorage;
                            TotalHits += site.Usage.Hits;
                            TotalStorage += site.Usage.Storage;
                            TotalVisits += site.Usage.Visits;
                            TotalRecentMonth = TotalRecentMonth + RecentMonth;
                            TotalRecentDay = TotalRecentDay + RecentDayHits; 
                            progressStatus = "Processing Site Collection Data for -- " + site.Url + " -- " + "and Databse - " + site.ContentDatabase.Name + " -->";

                            site.Close();
                            site.Dispose();
                        }
                    }
                    catch (SPException spEx) { ErrorLog("Error Module ProcessandPopulateLargeObjectData - " + spEx.Message); }
                    catch (Exception ex) { ErrorLog("Error Module ProcessandPopulateLargeObjectData - " + ex.Message); }

                    System.Threading.Thread.Sleep(60);


                    if (backgroundProcessCount <= siteCount)
                    {
                        backgroundWorker1.ReportProgress((backgroundProcessCount * 100) / (siteCount - 1));
                        //backgroundWorker1.ReportProgress((backgroundProcessCount));
                        backgroundProcessCount++;
                    }
                }
                #endregion

            });
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

            try
            {
                tableSiteCollectionStorageInfo = helper.CreateTabletoStoreSiteCollectionStorageInfo();
                tableListVersionInfo = helper.CreateTabletoStoreListVersionInfo();
                tableListLargeLists = helper.CreateTabletoStoreListVersionInfo();
                tableSiteACLs = helper.CreateTabletoStoreSiteACLs();
                tableSiteSolutions = helper.CreateTabletoStoreSiteSolutions();
                tableListTemplates = helper.CreateTableToStoreListTemplates();

                TotalHits = 0;
                TotalVisits = 0;
                TotalRecentMonth = 0;
                TotalStorage = 0;
                TotalBandwidth = 0;
                TotalDiscussionStorage = 0;

                tableSiteUsage = new DataTable();

                colUSite = new DataColumn();
                colUSite.ColumnName = "SiteCollection URL";

                colUBandWidth = new DataColumn();
                colUBandWidth.ColumnName = "Bandwidth";

                colURecentMonth = new DataColumn();
                colURecentMonth.ColumnName = "Recent Month";

                colUDiscussionStorage = new DataColumn();
                colUDiscussionStorage.ColumnName = "DiscussionStorage";

                colUHits = new DataColumn();
                colUHits.ColumnName = "Hits";

                colUStorage = new DataColumn();
                colUStorage.ColumnName = "Storage";

                colURecentDayHits = new DataColumn();
                colURecentDayHits.ColumnName = "RecentDayHits";

                colUDatabase = new DataColumn();
                colUDatabase.ColumnName = "Content Database";

                colLastContentModified = new DataColumn();
                colLastContentModified.ColumnName = "Last Content Modified";

                colLastSecurityModified = new DataColumn();
                colLastSecurityModified.ColumnName = "Last Security Modified";

                tableSiteUsage.Columns.Add(colUSite);
                //tableSiteUsage.Columns.Add(colUHits);
                tableSiteUsage.Columns.Add(colURecentDayHits);
                tableSiteUsage.Columns.Add(colURecentMonth);
                tableSiteUsage.Columns.Add(colUStorage);
                tableSiteUsage.Columns.Add(colUDatabase);
                tableSiteUsage.Columns.Add(colUBandWidth);
                tableSiteUsage.Columns.Add(colUDiscussionStorage);
                tableSiteUsage.Columns.Add(colLastContentModified);
                tableSiteUsage.Columns.Add(colLastSecurityModified);



                SPSiteCollection Sites = null;

                if (selectedDatabasesList.Contains("All Databases"))
                {
                    siteCount = webApp.Sites.Count;
                    Sites = webApp.Sites;
                    ProcessandPopulateLargeObjectData(Sites);
                }

                else if (!selectedDatabasesList.Contains("All Databases"))
                {
                    siteCount = FindTotalSiteCountFromSelectedDatabases();

                    foreach (SPContentDatabase db in webApp.ContentDatabases)
                    {
                        try
                        {
                            if (selectedDatabasesList.Contains(db.Name))
                            {
                                Sites = db.Sites;

                                ProcessandPopulateLargeObjectData(Sites);
                            }

                        }
                        catch (SPException spEx) { ErrorLog("Error Module backgroundWorker1_DoWork - " + spEx.Message); }
                        catch (Exception ex) { ErrorLog("Error Module backgroundWorker1_DoWork - " + ex.Message); }
                    }
                }

                //Populates Web Application Stats & usage summary 
                PopulatePortalStats();

                if (chkDisplayLargeSites.Checked == true)
                {
                    tableSiteCollectionStorageInfo.DefaultView.Sort = "Total Size in MB" + " DESC";
                    //gridSiteCollections.DataSource = tableSiteCollectionStorageInfo;
                    e.Result = tableSiteCollectionStorageInfo;
                }

            }
            catch (SPException spEx)
            {
                string err = spEx.Message;
                if (spEx.InnerException != null)
                    err = spEx.Message + "   " + spEx.InnerException.ToString();
                ErrorLog("Error occurred on backgroundWorker1_DoWork " + spEx.Message); 
                MessageBox.Show(null, err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                if (ex.InnerException != null)
                    err = ex.Message + "   " + ex.InnerException.ToString();

                ErrorLog("Error occurred on backgroundWorker1_DoWork " + ex.Message); 
                MessageBox.Show(null, err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
            //progressBar1.Increment(1); 
            toolStripStatusLabel2.Text = progressStatus + e.ProgressPercentage.ToString() + "%";
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 100;
            gridSiteCollections.DataSource = e.Result;
            toolStripStatusLabel2.Text = "";
            dataGridSiteUsageSummary.DataSource = tableSiteUsage;
            dataGridPortalStats.DataSource = tablePortalUsageStats;
            //progressBar1.Value = 0;
            timer1.Stop();

            //toolStripStatusLabelTime.Text = "";

        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            TimeSpan ts = DateTime.Now.Subtract(startDate);

            string sTime = "  ..." + ts.Minutes.ToString("00") +

               ":" + ts.Seconds.ToString("00") +

               ":" + ts.Milliseconds.ToString("000");

           toolStripStatusLabelTime.Text = sTime;
           toolStripProgressBar1.Increment(1);
           toolStripProgressBar1.PerformStep();

        }
        #endregion 

        #region Events 

        private void btnIdentifyLargeObjects_Click_1(object sender, EventArgs e)
        {
            if (cbListWebApps.SelectedItem != null && cbContentDabases.SelectedItem != null)
            {
                tabControl1.TabPages["tabWebApplicationInfo"].Show();
                tabControl1.SelectTab("tabWebApplicationInfo"); 
                tabControl1.TabIndex = 0;
                LargeSiteSize = txtLargeSiteSize.Text; 
                toolStripProgressBar1.Value = 0;
                toolStripStatusLabel2.Text = "Please, wait ...";
                backgroundProcessCount = 0; 
                LoadSiteCollections(webApp, "All");
                
                dataGridPortalStats.DataSource = null;
                toolStripStatusLabel2.Text = "Loading ... Thanks for your patience";

                try
                {
                    backgroundWorker1.RunWorkerAsync();
                    timer1.Start();
                    
                }
                catch (Exception ex)
                {
                    ErrorLog("Error occurred on event btnIdentifyLargeObjects_Click_1 or backgroundWorker1.RunWorkerAsync: " + ex.Message);
                    MessageBox.Show("Error occurred on event btnIdentifyLargeObjects_Click_1 or backgroundWorker1.RunWorkerAsync: " + ex.Message);
                }


                try
                {
                    if (chkIdentifyUnGhostedPages.Checked == true)
                        PopulateUnGhostedPagesandCheckedOutFiles();

                    if (chkDisplayUnlimitedListVersions.Checked == true)
                        gridListVersionInfo.DataSource = tableListVersionInfo;
                    if (chkDisplayLargeLists.Checked == true)
                        gridLargeLists.DataSource = tableListLargeLists;
                    if (chkDisplayLargeACLS.Checked == true)
                        gridSiteswithLargeACLs.DataSource = tableSiteACLs;

                    if (chkDisplayTemplates.Checked == true)
                    {
                        gridListTemplates.DataSource = tableListTemplates;
                        gridCustomSiteSolutions.DataSource = tableSiteSolutions;
                    }

                    tableDatabasesInfo = helper.CreateTabletoStoreDatabaseInfo();
                    LoadContentDBDetails(webApp);
                    gridDatabasesInfo.DataSource = tableDatabasesInfo;
                }
                catch (Exception ex)
                {
                    ErrorLog("Error occurred in one of the main event while populating additional data : " + ex.Message);
                    MessageBox.Show("Error occurred on event btnIdentifyLargeObjects_Click_1 or backgroundWorker1.RunWorkerAsync: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Please select the Web Application to identify large objects");
            }
        }

        /// <summary>
        /// DataGridView Mouse Click event to Load Sites with Large number of unique users (ACLs). 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridSiteswithLargeACLs_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {

                int rowIndex = gridSiteswithLargeACLs.HitTest(e.X, e.Y).RowIndex;

                if (rowIndex != -1)
                {
                    listUniqueACLs.Items.Clear();

                    if (gridSiteswithLargeACLs.Rows[rowIndex].Cells[0].Value != null)
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            using (SPSite site = new SPSite(gridSiteswithLargeACLs.Rows[rowIndex].Cells[0].Value.ToString()))
                            {
                                try
                                {
                                    using (SPWeb web = site.OpenWeb())
                                    {
                                        try
                                        {
                                            foreach (SPUser user in web.SiteUsers)
                                            {
                                                try
                                                {
                                                    listUniqueACLs.Items.Add(new ListItem(user.Name));
                                                    listUniqueACLs.Update();
                                                }
                                                catch (SPException spEx) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + spEx.Message); }
                                                catch (Exception ex) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + ex.Message); }
                                            }
                                        }
                                        catch (SPException spEx) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + spEx.Message); }
                                        catch (Exception ex) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + ex.Message); }
                                    }
                                }
                                catch (SPException spEx) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + spEx.Message); }
                                catch (Exception ex) { ErrorLog("Error event gridSiteswithLargeACLs_MouseClick - " + ex.Message); }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message);
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// DataGridView Mouse click event to Load Content Database Details
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridDatabasesInfo_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                int rowIndex = gridDatabasesInfo.HitTest(e.X, e.Y).RowIndex;

                if (rowIndex != -1)
                {
                    listSites.Items.Clear();

                    if (gridDatabasesInfo.Rows[rowIndex].Cells[7].Value != null)
                    {
                        string strDBGUID = gridDatabasesInfo.Rows[rowIndex].Cells[7].Value.ToString();
                        dbName = gridDatabasesInfo.Rows[rowIndex].Cells[1].Value.ToString();
                        Guid dbGuid = new Guid(strDBGUID);

                        SPContentDatabaseCollection databases = webApp.ContentDatabases;
                        SPContentDatabase db = webApp.ContentDatabases[dbGuid];

                        foreach (SPSite site in db.Sites)
                        {
                            try
                            {
                                listSites.Items.Add(new ListItem(site.Url));
                            }
                            catch (SPException spEx) { ErrorLog("Error event gridDatabasesInfo_MouseClick - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error event gridDatabasesInfo_MouseClick - " + ex.Message); }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdMajorVersionLLimit_CheckedChanged(object sender, EventArgs e)
        {
            txtSetMajorVersionLimit1.Enabled = true;
            txtSetMajorVersionLimit2.Enabled = false;
            txtMajorwithMinorVersionLimit.Enabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rdMajorandMinorVersionLimit_CheckedChanged(object sender, EventArgs e)
        {
            txtMajorwithMinorVersionLimit.Enabled = true;
            txtSetMajorVersionLimit2.Enabled = true;
            txtSetMajorVersionLimit1.Enabled = false;
            MessageBox.Show("This tool will update major and minor version settings with the new version limit, only if Minor version is already enabled in the selected list(s). If you want to enable Minor version irrespective of the previous settings, then please select Force Minor version check box");
        }

        /// <summary>
        /// Backup UnGhosted Pages before you perform Reset to Site Defintion
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBackupUnGhostedPages_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowNewFolderButton = true;
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            string foldername = this.folderBrowserDialog1.SelectedPath;

            if (result == DialogResult.OK)
            {
                foreach (DataGridViewRow row in gridCustomizedPages.Rows)
                {
                    string url = row.Cells["Url"].Value.ToString();

                    using (SPSite site = new SPSite(url))
                    {
                        try
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                try
                                {
                                    SPFile file = web.GetFile(url);

                                    if (file.CustomizedPageStatus == SPCustomizedPageStatus.Customized)
                                    {
                                        // Open the binary data
                                        byte[] data = file.OpenBinary();
                                        string targetDirectory = foldername;
                                        string webName = "";

                                        if (web.Url.Contains("https://"))
                                            webName = web.Url.Replace("https://", "").Replace("/", "_").Replace(".", "");
                                        else if (web.Url.Contains("http://"))
                                            webName = web.Url.Replace("http://", "").Replace("/", "_").Replace(".", "");

                                        targetDirectory = System.IO.Path.Combine(foldername, webName);
                                        Directory.CreateDirectory(targetDirectory);

                                        string targetFile = targetDirectory + "\\" + file.Name;

                                        if (File.Exists(targetFile))
                                            File.Delete(targetFile);

                                        using (FileStream stream = new FileStream(targetFile, FileMode.CreateNew))
                                        {
                                            // Save the file
                                            BinaryWriter writer = new BinaryWriter(stream);
                                            writer.Write(data, 0, (int)file.Length);
                                            writer.Close();
                                            stream.Close();
                                        }
                                    }
                                }
                                catch (SPException spEx) { ErrorLog("Error Event btnBackupUnGhostedPages_Click - " + spEx.Message); }
                                catch (Exception ex) { ErrorLog("Error Event btnBackupUnGhostedPages_Click - " + ex.Message); }
                            }
                        }
                        catch (SPException spEx) { ErrorLog("Error Event btnBackupUnGhostedPages_Click - " + spEx.Message); }
                        catch (Exception ex) { ErrorLog("Error Event btnBackupUnGhostedPages_Click - " + ex.Message); }
                    }
                }
                MessageBox.Show("Customized pages are backed up successfully");
            }
        }

        private void btnGhostPages_Click(object sender, EventArgs e)
        {
            string msg = "Are you sure you want to Ghost pages back to file system";
            if (MessageBox.Show(msg, "Confirm Ghosting", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                foreach (DataGridViewRow row in gridCustomizedPages.SelectedRows)
                {
                    try
                    {
                        string url = row.Cells["Url"].Value.ToString();

                        using (SPSite site = new SPSite(url))
                        {
                            try
                            {
                                using (SPWeb web = site.OpenWeb())
                                {
                                    try
                                    {
                                        SPFile file = web.GetFile(url);
                                        file.RevertContentStream();
                                    }
                                    catch (SPException spEx) { ErrorLog("Error Event btnGhostPages_Click - " + spEx.Message); }
                                    catch (Exception ex) { ErrorLog("Error Event btnGhostPages_Click - " + ex.Message); }
                                }
                            }
                            catch (SPException spEx) { ErrorLog("Error Event btnGhostPages_Click - " + spEx.Message); }
                            catch (Exception ex) { ErrorLog("Error Event btnGhostPages_Click - " + ex.Message); }
                        }
                        MessageBox.Show("Selected Pages are Ghosted Successfully");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void btnIdentifyUnGhostandCheckedOutFiles_Click(object sender, EventArgs e)
        {
            try
            {
                if (webApp == null)
                {
                    if (cbListWebApps.SelectedItem != null)
                    {

                        string strWebApp = cbListWebApps.SelectedItem.ToString();
                        Uri strUrl = new Uri(helper.ReturnWebAppURL(strWebApp));
                        webApp = SPWebApplication.Lookup(strUrl);
                    }
                    else
                    {
                        MessageBox.Show("Please select web application to continue this operation");
                        return;
                    }
                }

                string msg = "Please note this operation may take long duration depending on the size of the databases. It is recommended that you perform this operation during out of office or less peak hours.";

                if (MessageBox.Show(msg, "Confirm Execution", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    PopulateUnGhostedPagesandCheckedOutFiles();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnForceCheckIn_Click(object sender, EventArgs e)
        {
            string msg = "Are you sure you want to Forcefully CheckIn documents, please note this will change the modified by and modified date properties of the document to the process account name";

            if (MessageBox.Show(msg, "Confirm Force CheckIn", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                try
                {
                    foreach (DataGridViewRow row in dataGridCheckedOutDocs.SelectedRows)
                    {

                        string url = row.Cells["Url"].Value.ToString();

                        using (SPSite site = new SPSite(url))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                try
                                {
                                    string checkInMsg = "Checkd In forcefully by administrator programmatically";
                                    string folderUrl = url.Replace(web.Url + "//", "");
                                    SPFile file = web.GetFile(folderUrl);

                                    if (radioMajorCheckIn.Checked == true)
                                        file.CheckIn(checkInMsg, SPCheckinType.MajorCheckIn);
                                    else if (radioMinorCheckIn.Checked == true)
                                        file.CheckIn(checkInMsg, SPCheckinType.MinorCheckIn);
                                    else
                                        file.CheckIn(checkInMsg, SPCheckinType.OverwriteCheckIn);
                                }
                                catch (System.IO.IOException ioEx)
                                {
                                }
                            }
                        }
                    }
                    MessageBox.Show("Documents successfully Checked In");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnUnDoCheckOutFiles_Click(object sender, EventArgs e)
        {
            string msg = "Are you sure you want to Undo check out on selected documents, please note any changes that are done by the checked out user will be lost";

            if (MessageBox.Show(msg, "Confirm UnDo Check Out", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            {
                foreach (DataGridViewRow row in dataGridCheckedOutDocs.SelectedRows)
                {
                    try
                    {
                        string url = row.Cells["Url"].Value.ToString();

                        using (SPSite site = new SPSite(url))
                        {
                            using (SPWeb web = site.OpenWeb())
                            {
                                try
                                {
                                    SPFile file = web.GetFile(url);
                                    file.UndoCheckOut();
                                }
                                catch (System.IO.IOException ioEx)
                                {

                                }
                            }
                        }
                        MessageBox.Show("Un do documents check out successful");
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void chkIdentifyUnGhostedPages_CheckedChanged(object sender, EventArgs e)
        {
            string msg = "";
            if (chkIdentifyUnGhostedPages.Checked == true)
                msg = "Please note this option may take a long duration depending on the size of the databases. It is recommended that you perform this operation during out of office or less peak hours.";

            if (MessageBox.Show(msg, "Confirm Execution", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No)
            {
                chkIdentifyUnGhostedPages.Checked = false;
            }
        }

        private void cbListWebApps_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string strWebApp = cbListWebApps.SelectedItem.ToString();
                webAppUrl = helper.ReturnWebAppURL(strWebApp);
                webApp = SPWebApplication.Lookup(new Uri(webAppUrl));
                cbContentDabases.Items.Clear();

                cbContentDabases.Items.Add(new ListItem("All Databases", "All Databases"));
                cbContentDabases.SelectedIndex = 0;

                foreach (SPContentDatabase db in webApp.ContentDatabases)
                {
                    try
                    {
                        cbContentDabases.Items.Add(new ListItem(db.Name, db.Id.ToString()));
                    }
                    catch (SPException spEx) { ErrorLog("Error Module cbListWebApps_SelectedIndexChanged - " + spEx.Message); }
                }
            }
            catch (SPException spEx) { ErrorLog("Error Module cbListWebApps_SelectedIndexChanged - " + spEx.Message); }
            catch (Exception ex) { ErrorLog("Error Module cbListWebApps_SelectedIndexChanged - " + ex.Message); }
        }

        private void txtLargeSiteSize_Click(object sender, EventArgs e)
        {
            txtLargeSiteSize.Text = "";
        }

        private void btnLimitVersions_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to limit the version settings for the selected list or libraries ? ", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {

                    if ((rdMajorandMinorVersionLimit.Checked == true || rdMajorVersionLLimit.Checked == true) && gridListVersionInfo.SelectedRows.Count > 0)
                    {
                        foreach (DataGridViewRow row in gridListVersionInfo.SelectedRows)
                        {
                            if (row.Cells["Site Url"].Value != null)
                            {
                                SPSecurity.RunWithElevatedPrivileges(delegate()
                                {
                                    using (SPSite site = new SPSite(row.Cells["Site Url"].Value.ToString()))
                                    {
                                        using (SPWeb web = site.OpenWeb())
                                        {
                                            try
                                            {
                                                if (row.Cells["List Name"].Value != null)
                                                {
                                                    SPList list = web.Lists[row.Cells["List Name"].Value.ToString()];

                                                    if (list.MajorVersionLimit.Equals(0) && rdMajorVersionLLimit.Checked == true)
                                                        list.MajorVersionLimit = Convert.ToInt32(txtSetMajorVersionLimit1.Text);

                                                    if (list.EnableMinorVersions == true && list.MajorWithMinorVersionsLimit.Equals(0) && rdMajorandMinorVersionLimit.Checked == true && chkForceMinorVersionLimit.Checked == false)
                                                    {
                                                        list.MajorVersionLimit = Convert.ToInt32(txtSetMajorVersionLimit2.Text);
                                                        list.MajorWithMinorVersionsLimit = Convert.ToInt32(txtMajorwithMinorVersionLimit.Text);
                                                    }
                                                    if (list.MajorWithMinorVersionsLimit.Equals(0) && rdMajorandMinorVersionLimit.Checked == true && chkForceMinorVersionLimit.Checked == true)
                                                    {
                                                        list.EnableMinorVersions = true;
                                                        list.MajorVersionLimit = Convert.ToInt32(txtSetMajorVersionLimit2.Text);
                                                        list.MajorWithMinorVersionsLimit = Convert.ToInt32(txtMajorwithMinorVersionLimit.Text);
                                                    }

                                                    list.Update();
                                                }
                                            }
                                            catch (SPException spEx) { ErrorLog("Error event btnLimitVersions_Click - " + spEx.Message); }
                                            catch (Exception ex) { ErrorLog("Error Module - PopulateACLInfoGrid - " + ex.Message); }

                                        }
                                    }

                                });
                            }
                            MessageBox.Show(null, "Operation successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(null, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRemoveACLs_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Are sure you want to remove all users from the selected sites.  Please note removing users from site collection will remove users from all subsites and child objects.  Click Yes to continue or No to cancel", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    foreach (DataGridViewRow row in gridSiteswithLargeACLs.SelectedRows)
                    {
                        if (row.Cells[0].Value != null)
                        {
                            string url = row.Cells[0].Value.ToString();

                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                using (SPSite site = new SPSite(url))
                                {
                                    try
                                    {

                                        SPWeb web = site.RootWeb;

                                        for (int i = web.SiteUsers.Count - 1; i >= 0; --i)
                                        {
                                            if (!web.SiteUsers[i].Name.Equals("System Account") && !web.SiteUsers[i].IsSiteAdmin)
                                            {
                                                if (chkDoNotRemoveADGroups.Checked == true)
                                                {
                                                    if (web.SiteUsers[i].IsDomainGroup == false)
                                                        web.SiteUsers.RemoveByID(web.SiteUsers[i].ID);
                                                }
                                                else
                                                {
                                                    web.SiteUsers.RemoveByID(web.SiteUsers[i].ID);
                                                }
                                            }
                                        }
                                        web.AllowUnsafeUpdates = true;
                                        web.Update();
                                    }
                                    catch (SPException spEx) { ErrorLog("Error event btnRemoveACLs_Click_1 - " + spEx.Message); }
                                    catch (Exception ex) { ErrorLog("Error event btnRemoveACLs_Click_1 - " + ex.Message); }
                                }
                            });
                            }
                    }
                    MessageBox.Show(null, "SharePoint Site users are successfully deleted from the selected site collection", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    PopulateACLInfoGrid();
                    listUniqueACLs.Items.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(null, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        ////private void chkShowSitesfromDBs_CheckedChanged(object sender, EventArgs e)
        //{
        //    if (cbListWebApps.SelectedItem != null && cbContentDabases.SelectedItems.Count > 0)
        //    {
        //        SPSiteCollection siteCollections = null;

        //        if (selectedDatabasesList.Contains("All Databases"))
        //        {
        //            siteCollections = webApp.Sites;
        //        }
        //        else
        //        {

        //            cbListSiteCollections.Items.Clear();
        //            foreach (SPContentDatabase db in webApp.ContentDatabases)
        //            {
        //                try
        //                {
        //                    if (selectedDatabasesList.Contains(db.Name))
        //                    {
        //                        siteCollections = db.Sites;

        //                        foreach (SPSite site in siteCollections)
        //                        {

        //                            try
        //                            {
        //                                string siteName = site.Url.ToString();
        //                                cbListSiteCollections.Items.Add(new ListItem(siteName, site.Url.ToString()));
        //                                cbListSiteCollections.Update();

        //                            }
        //                            catch (SPException spEx) { ErrorLog(spEx.Message); }
        //                            catch { }

        //                            site.Dispose();
        //                        }
        //                    }


        //                }
        //                catch (SPException spEx) { ErrorLog("Error Module chkShowSitesfromDBs_CheckedChanged - " + spEx.Message); }
        //                catch (Exception ex) { ErrorLog("Error Module chkShowSitesfromDBs_CheckedChanged - " + ex.Message); }
        //            }

        //        }
        //    }
        //}

        private void cbContentDabases_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cbContentDabases.SelectedItems.Count > 0)
                {
                    selectedDatabasesList.Clear(); 
                    //int Count = 0; 
                    foreach (ListItem item in cbContentDabases.SelectedItems)
                    {
                        try
                        {
                            if (item != null)
                            {
                                selectedDatabasesList.Add(item.Text);
                                //Count = Count + 1;
                            }
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }


        private void selectLockOperation_CheckedChanged(object sender, EventArgs e)
        {
            txtSiteLockStatus.Text = "";
            cblistSiteCollectionstoLock.SelectionMode = SelectionMode.MultiExtended;
            LoadSiteCollections(webApp, "All");
        }

        private void selectShowLockedSites_CheckedChanged(object sender, EventArgs e)
        {
            txtSiteLockStatus.Text = "";
            //Load Site Collection on the cblistSiteCollectionstoLock list box control
            LoadSiteCollections(webApp, "ShowLockedSites");
        }

        private void cbListSiteCollectionsforWebUsage_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string siteUrl = cbListSiteCollectionsforWebUsage.Text;

                uwebTotalHits = 0;
                uwebTotalRecentMonth = 0;
                uwebTotalMostRecentDayHits = 0;

                gridWebUsageSummary.DataSource = null;
                dataGridWebUsageData.DataSource = null;

                gridWebUsageSummary.Refresh();
                dataGridWebUsageData.Refresh();

                populateWebUsageData(siteUrl);
                populateWebUsageSummary();

                if (chkDailyUsageData.Checked == true)
                    populateDailyWebUsageData(siteUrl);
            }
            catch (DataException dataEx)
            {
                ErrorLog("Unable to get site usage info: " + dataEx.Message);
            }
            catch (Exception ex)
            {
                ErrorLog("Unable to get site usage info: " + ex.Message);
            }
        }

        private void btnLockSites_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    //SPGlobalAdmin ga = new SPGlobalAdmin();
                    //SPVirtualServer v = ga.OpenVirtualServer(new Uri(cbListWebApps.Text));
                    bool isSuccess = false;

                    if (cblistSiteCollectionstoLock.SelectedItem != null)
                    {
                        foreach (ListItem item in cblistSiteCollectionstoLock.SelectedItems)
                        {
                            string siteUrl = item.Text;
                            using (SPSite site = new SPSite(siteUrl))
                            {

                                try
                                {
                                    site.AllowUnsafeUpdates = true;
                                    if (rbPreventRead.Checked == true)
                                    {
                                        site.ReadLocked = true;
                                        site.WriteLocked = true;
                                        site.LockIssue = txtLockComment.Text;
                                        isSuccess = true;
                                    }
                                    if (rbPreventWrite.Checked == true)
                                    {
                                        site.ReadLocked = false;
                                        site.WriteLocked = true;
                                        site.LockIssue = txtLockComment.Text;
                                        isSuccess = true;
                                    }
                                    if (rbNoLock.Checked == true)
                                    {
                                        site.ReadLocked = false;
                                        site.WriteLocked = false;
                                        site.LockIssue = txtLockComment.Text;
                                        isSuccess = true;
                                    }
                                }
                                catch (SPException spEx) { ErrorLog("Error Module btnLockSites_Click - " + spEx.Message); 
                                MessageBox.Show("Error occurred - " + spEx.Message); 
                                }
                                catch (Exception ex) { ErrorLog("Error Module btnLockSites_Click - " + ex.Message);
                                MessageBox.Show("Error occurred - " + ex.Message); 
                                }

                            }
                        }
                    }

                    if (isSuccess == true)
                        MessageBox.Show("Selected sites are blocked successfully");
                });
            }
            catch (SPException spEx)
            {
                MessageBox.Show(spEx.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cblistSiteCollectionstoLock_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(cblistSiteCollectionstoLock.Text))
                {
                    if (site.WriteLocked == true)
                        txtSiteLockStatus.Text = "Write Locked";
                    else if (site.ReadLocked == true)
                        txtSiteLockStatus.Text = "No Access to site";
                    else if (site.ReadOnly == true)
                        txtSiteLockStatus.Text = "Read only lock";
                    else
                        txtSiteLockStatus.Text = "Not Locked";
                }
            }
            catch (SPException spEx)
            {
                if (spEx.Message.Contains("blocked"))
                    txtSiteLockStatus.Text = "Write Locked";
                else
                    ErrorLog("Error occured: " + spEx.Message);
            }
            catch (Exception ex)
            {
                ErrorLog("Error occured: " + ex.Message);
            }
        }

        private void chkIdentifyUnGhostedPages_CheckedChanged_1(object sender, EventArgs e)
        {
            string str = "Please note selecting this option could take more time to process the results in a large SharePoint farm.  You can select one or more content databases instead of selecting All databases. Are you sure that you want to run this option ?";

            if (MessageBox.Show(str, "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
            {
                chkIdentifyUnGhostedPages.Checked = false;
                return;
            }
        }

        private void chkDisplayLargeACLS_CheckedChanged(object sender, EventArgs e)
        {
            string str = "Please note selecting this option could take more time to process the results in a large SharePoint farm.  You can select one or more content databases instead of selecting All databases. Are you sure that you want to run this option ?";

            if (MessageBox.Show(str, "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
            {
                chkDisplayLargeACLS.Checked = false;
                return;
            }
        }

        #endregion 


    }
}
         


       